package com.jnu.myaccount.record;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.jnu.myaccount.MainActivity;
import com.jnu.myaccount.R;
import com.jnu.myaccount.adapter.ItemAdapter;
import com.jnu.myaccount.data.Data;
import com.jnu.myaccount.data.GridItems;
import com.jnu.myaccount.function.home.HomeFragment;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class IncomeFragment extends Fragment implements View.OnClickListener {


    private GridView mIncomeGridView;
    private ItemAdapter mItemAdapter;
    public static String[] itemNames_Income = new String[]{"投资理财", "工资薪水","人情礼物","借债","社会福利","租赁收入","利润收入","其他"};
    public static int[] itemImage_Income = new int[]{R.drawable.detail,R.drawable.gongzi,R.drawable.fuli,R.drawable.qianzhai,R.drawable.liwu,R.drawable.zulin,R.drawable.lirun,R.drawable.qita};
    private TextView mTv;
    private int mIv_id;
    private ImageView mIv;
    private EditText mMark;
    private EditText mCost;
    private Calendar cal;
    private Button mButton;
    private TextView tvShowDialog;//选择日期和时间的弹窗
    private TextView tvShowDialog2;
    public Bundle bundle;
    public int bundle_position=-1;
    public int mpostion;//记录修改记录的位置


    private int mYear, mMonth, mDay, mHour, mMinute;



    public IncomeFragment() {
        // Required empty public constructor
    }


    public static PaidFragment newInstance() {
        PaidFragment fragment = new PaidFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取当前日期
        getDate();
        if (getArguments() != null) {

        }
    }

    private void getDate() {
        cal=Calendar.getInstance();
        mYear =cal.get(Calendar.YEAR);       //获取年月日时分秒
        Log.i("wxy","year"+ mYear);
        mMonth =cal.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        mDay =cal.get(Calendar.DAY_OF_MONTH);
        mHour =cal.get(Calendar.HOUR_OF_DAY)+8;
        mMinute =cal.get(Calendar.MINUTE);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootview=inflater.inflate(R.layout.fragment_income, container, false);
        tvShowDialog=rootview.findViewById(R.id.show_date);
        tvShowDialog.setOnClickListener(this);
        tvShowDialog2=rootview.findViewById(R.id.show_time);
        tvShowDialog2.setOnClickListener(this);
        mButton=rootview.findViewById(R.id.show_creat);
        mButton.setOnClickListener(this);
        TextView tv=rootview.findViewById(R.id.show_type_name);//获取活动名称
        TextView pd=rootview.findViewById(R.id.show_count);//获取金额
        EditText mk=rootview.findViewById(R.id.show_mark_name);//获取备注
        TextView d=rootview.findViewById(R.id.show_date);//获取日期
        TextView t=rootview.findViewById(R.id.show_time);//获取事件
        Button b=rootview.findViewById(R.id.show_creat);//获取按钮
        ImageView iv=rootview.findViewById(R.id.show_type_iv);//获取活动图片
        getDate();

        Bundle bundle = getActivity().getIntent().getExtras();//利用bundle判断如果是修改的行为动作
        if(bundle!=null&&bundle.getString("type").equals("Income")) {
            this.bundle=bundle;
            Log.i("position2",bundle.getInt("position")+"");
            Log.i("type2",bundle.getString("type"));
            int position=bundle.getInt("position");
            bundle_position=position;
            mpostion=position;
            Serializable serializable = bundle.getSerializable("DataInfo");
            if (serializable != null && serializable instanceof Data) {
                Data g = (Data) serializable;
                tv.setText(g.getName());
                pd.setText(String.valueOf(g.getCost()));
                mk.setText(g.getItemMark());
                g.getTime();
                d.setText(g.mDate);
                t.setText(g.mTime);
                b.setText("修改记录");
                mIv_id=g.getPictureID();
                iv.setImageResource(mIv_id);
                for(int i=0;i<itemImage_Income.length;i++){
                    if(itemImage_Income[i]==g.getPictureID()){
                        bundle_position=g.getPictureID();
                    }
                }
                initGridView(rootview);
            }
        }
        else {
            initGridView(rootview);
            mIv_id=itemImage_Income[5];
            d.setText(mYear+"-"+(mMonth+1)+"-"+mDay);
            DecimalFormat df=new DecimalFormat("00");
            t.setText(df.format(mHour)+":"+df.format(mMinute));
        }
        return rootview;
    }

    private void initGridView(View view) {
        mIncomeGridView = view.findViewById(R.id.show_type_items);
        mTv=view.findViewById(R.id.show_type_name);
        mIv=view.findViewById(R.id.show_type_iv);
        mMark=view.findViewById(R.id.show_mark_name);
        mCost=view.findViewById(R.id.show_count);

        List<GridItems> provinceBeanList = new ArrayList<>();
        for (int i = 0; i < itemNames_Income.length; i++) {
            GridItems mItemsType = new GridItems(itemNames_Income[i],itemImage_Income[i]);
            provinceBeanList.add(mItemsType);
        }
        mItemAdapter = new ItemAdapter(getActivity(), provinceBeanList);
        if(bundle!=null){
            mItemAdapter.setSelected(bundle_position);
        }
        mIncomeGridView.setAdapter(mItemAdapter);

        mIncomeGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                             @Override
                                             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                 int iv=itemImage_Income[position];
                                                 mItemAdapter.changeSelected(position);//点击监听
                                                 mIv_id=iv;
                                                 TextView tv=view.findViewById(R.id.tv1);
                                                 mTv.setText(tv.getText());
                                                 mIv.setImageResource(iv);
                                             }
                                         }
        );
        mIncomeGridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mItemAdapter.changeSelected(position);//选中监听
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override//生成按钮的点击事件响应
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.show_creat://生成按钮的响应
                Date mdate=new Date(mYear, mMonth, mDay, mHour, mMinute);//生成Date成员
                String mName=mTv.getText().toString();//生成名字
                String mMark=this.mMark.getText().toString();//生成备注
                Double mCost=Double.parseDouble(this.mCost.getText().toString());//生成金额
                Data mDate=new Data(mName,mCost,mMark,mdate,mIv_id);//一个完整的Data成员
                //传值部分
                if(bundle_position!=-1){//返回修改的值
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DataInfo", mDate);
                    bundle.putString("type","paidEdit");
                    Log.i("type",bundle.getString("type"));
                    HomeFragment.mark_num=-1;//打开首页的数据开关
                    bundle.putInt("position",mpostion);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                else{
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("DataInfo", mDate);
                    bundle.putString("type","add");
                    HomeFragment.mark_num=-1;//打开首页的数据开关
                    Log.i("type",bundle.getString("type"));
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

                break;
            case R.id.show_date://选择年月日
                DatePickerDialog.OnDateSetListener listener=new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        mYear=year;
                        mMonth=month;
                        mDay=dayOfMonth;
                        tvShowDialog.setText(year+"-"+(++month)+"-"+dayOfMonth);      //将选择的日期显示到TextView中,因为之前获取month直接使用，所以不需要+1，这个地方需要显示，所以+1
                    }


                };
                DatePickerDialog dialog=new DatePickerDialog(getActivity(), 0,listener, mYear, mMonth, mDay);//后边三个参数为显示dialog时默认的日期，月份从0开始，0-11对应1-12个月
                dialog.show();
                break;
            case R.id.show_time://选择时间
                //弹窗
                TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
                        new TimePickerDialog.OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                mHour=hourOfDay;
                                mMinute=minute;
                                String date = String.format("%d:%d", hourOfDay, minute);
                                tvShowDialog2.setText(date);
                            }
                        }, 0, 0, true);
                timePickerDialog.show();
                break;
        }
    }
}